<template>
  <div class="about">
    <el-select ref="select" v-model="selectVal" :disabled="disabled" :placeholder="placeholders" size="mini"
               :style="{ width: widths }" @blur="clearData" clearable @visible-change="visibleChange"
               @clear="clearSelect"
    >
      <el-input v-model="keyWordFilter" placeholder="搜索姓名、手机号、机构名称"
                prefix-icon="el-icon-search"
                @input="handleInput" @clear="clear" clearable :validate-event="false" style="position: sticky; top: 0;"
      ></el-input>
      <el-option key="id" hidden :value="selectVal" :label="selectItem.userName">
      </el-option>
      <div ref="container" class="down">
        <ul ref="list">
          <li class="liList" v-for="(item, index) in searchList" :key="index" @click.stop="handleSearchList(item)"
              :style="{ background: isActive(item) ? '#f5f7fa' : '#fff' }"
          >
            <div class="liFlex">
              <div class="laftText">
                <div class="name">{{ item.userName }}</div>
                <div>{{ item.phonenumber }}</div>
                <div>{{ item.deptName }}</div>
              </div>
              <i v-if="isActive(item)" class="icon el-icon-success"></i>
            </div>
          </li>
          <li v-show="searchResult" style="text-align: center">暂无搜索结果</li>
          <li v-show="!searchResult&&searchList.length===0" style="text-align: center">暂无数据</li>
          <li v-if="loading" style="text-align: center">加载中...</li>
        </ul>
      </div>
    </el-select>
  </div>
</template>
<script>
import { getWorkOrderPerson } from '@/api/houseManagement/workOrderPerson'

export default {
  name: 'Dorpdown',
  props: {
    url: {
      type: String,
      default: () => null
    },
    widths: {
      type: String,
      default: () => null
    },
    disabled: {
      type: Boolean,
      default: () => false
    },
    placeholders: {
      type: String,
      default: () => null
    },
    value: {
      type: [String, Number, Object],
      default: null
    },
    workOrderPersonType: {
      default: {}
    }
  },
  data() {
    return {
      selectVal: '', // select框的绑定值
      selectName: '', // select框显示的name
      keyWordFilter: '', // 搜索框绑定值，用作过滤
      solist: [], // 搜索存储列表
      searchList: [], // 接口返回搜索
      loading: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: '',
        roleKey: '',
        search: ''
      },
      // 总条数
      total: 0,
      searchResult: false,
      timer: null,
      selectItem: {}
    }
  },
  watch: {
    keyWordFilter: {
      handler(v) {
        if (!v) {
          this.searchResult = false
          this.searchList = []
        }
      }
    },
    value: {
      // 父组件使用选择的值回显给子组件
      immediate: true,
      handler(newValue) {
        this.selectVal = newValue
      }
    },
    searchResult(n) {
      console.log(n)
    }
  },
  created() {
    this.initData()
  },
  mounted() {
    this.$nextTick(() => {
      this.scrollToBottom()
    })
  },
  beforeDestroy() {
    // 移除滚动事件监听
    window.removeEventListener('scroll', this.handleScroll, true)
  },
  methods: {
    //初始化数据
    initData() {
      let roleKey = this.workOrderPersonType.roleKey || 'maintenance'
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        keyword: '',
        roleKey: roleKey,
        search: ''
      }
      getWorkOrderPerson(this.queryParams).then(res => {
        this.searchList = res.data
        this.selectItem = this.searchList.find(item => item.userId === this.value) || {}
        this.selectVal = this.selectItem.userId? this.selectItem.userId : ''
      }).catch(err => {
        this.searchList = []
      })
    },
    isActive(item) {
      return this.selectVal === item.userId // 这里的判断条件可以根据具体情况来定
    },
    scrollToBottom() {
      const container = this.$refs.container
      const list = this.$refs.list
      // 滚动到底部
      list.scrollTop = container.offsetHeight - list.offsetHeight
      // 监听滚动事件
      list.addEventListener('scroll', this.handleScroll)
    },
    handleScroll() {
      const container = this.$refs.container
      const list = this.$refs.list
      // 判断是否滚动到底部
      if (
        list.scrollTop >=
        container.offsetHeight - 60 // 在底部前10像素进行判断，可根据需要调整
      ) {
        console.log(list.offsetHeight, 'list.offsetHeight')
        // 在这里执行滚动到底部后的逻辑
        if (this.searchList.length < this.total) {
          this.queryParams.pageNum++
          this.search()
        }
      }
    },
    clearData() {
      this.keyWordFilter = ''
      this.queryParams.pageNum = 1
    },
    visibleChange(e) {
      if (!e) {
        // this.searchList = []
        console.log('隐藏')
        this.clearData()
      } else {
        console.log('显示')
        this.initData()
        // this.search()
      }
    },
    // 根据关键字搜索
    handleInput() {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        this.searchList = []
        this.queryParams.pageNum = 1
        this.queryParams.pageSize = 30
        this.search()
      }, 300)
    },
    // 模拟搜索防抖
    async search() {
      this.queryParams.search = this.keyWordFilter
      this.loading = true
      const res = await getWorkOrderPerson(this.queryParams)
      if (res && res.code === 200) {

        this.searchList = [...this.searchList, ...res.data]
        const map = new Map()
        const uniqueList = this.searchList.reduce((acc, item) => {
          if (!map.has(item.userId)) {
            map.set(item.userId, true)
            acc.push(item)
          }
          return acc
        }, [])
        this.searchList = uniqueList
        this.loading = false
        console.log(this.searchList, 'dorpdown')
        if (this.searchList.length === 0) {
          this.searchResult = true
        } else {
          this.searchResult = false
        }
        // this.total = res.data.count
      }
    },
    // 搜索框图标清空
    clear() {
      this.searchList = []
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 20
    },
    //   搜索列表点击
    handleSearchList(item) {
      this.selectVal = item.userId
      item.jobNumber = item.userId
      this.selectItem = item
      this.$emit('modelClass', this.selectItem)
      this.$emit('input', this.selectVal);
      this.visibleChange()
      this.$refs.select.blur()
    },

    //   清空值v-model的select值
    clearSelect() {
      console.log('清空值')
      this.selectVal = ''
      this.selectItem = {}
      console.log('this.selectItem',this.selectItem)
      this.$emit('input', this.selectVal)
      this.$emit('modelClass', this.seletItem)
    },
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-scrollbar__bar {
  overflow-x: hidden;
}

::v-deep .el-input--mini .el-input__inner {
  height: 32px;
}

.down {
  ul {
    padding: 0;
    //overflow-y: scroll;
    margin: 0;
    list-style: none;

    &::-webkit-scrollbar {
      /*滚动条整体样式*/
      width: 8px;
      /*高宽分别对应横竖滚动条的尺寸*/
      height: 1px;
    }

    &::-webkit-scrollbar-thumb {
      /*滚动条里面小方块*/
      border-radius: 10px;
      background: #cccccc;
      box-shadow: inset 0 0 5px #cccccc;
    }

    //滚动条底层颜色!
    &::-webkit-scrollbar-track {
      border-radius: 10px;
      background: #fdf8f5;

      /*滚动条里面轨道*/
      box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.1);
    }

    li {
      overflow: hidden; // 溢出隐藏
      white-space: nowrap; // 强制一行
      text-overflow: ellipsis; // 文字溢出显示省略号
      cursor: pointer;
      color: #606266;
      padding: 4px 0;

      &:hover {
        // color: rgb(0, 81, 255);
        background: #f5f7fa;
      }

      .liFlex {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 10px;

        .laftText {
          color: #B7B7B7;
          font-size: 14px;

          .name {
            color: #000;
            font-size: 16px;
            margin-bottom: 5px;
          }
        }

        .icon {
          color: #0caaf0;
          font-size: 28px;
        }
      }

    }

    .liList {
      border-top: 1px solid #e4e4e4;

      &:first-child {
        border-top: none;
      }
    }

  }
}
</style>
